﻿using DotNet.Utilities;
using JinfuyuanProject.Entity;
using JinfuyuanProject.Repository;
using JinfuyuanProject.Repository.Interface;
using JinfuyuanProject.Service.Interface;
using MongoDB.Driver.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JinfuyuanProject.Service
{
    public class ServiceDoService : IServiceDoService
    {
        private readonly IServiceDoRepository _serviceDoRepository;
        private readonly IServicesRepository _servicesRepository;
        private readonly IContractRepository _contractRepository;
        private readonly IParturientRepository _parturientRepository;
        private readonly IBabyRepository _babyRepository;
        private JinfuyuanDbContext _db;

        public ServiceDoService(
            IServiceDoRepository serviceDoRepository,
            IServicesRepository servicesRepository,
            IContractRepository contractRepository,
            IParturientRepository parturientRepository,
            IBabyRepository babyRepository, JinfuyuanDbContext db)
        {
            _serviceDoRepository = serviceDoRepository;
            _servicesRepository = servicesRepository;
            _contractRepository = contractRepository;
            _parturientRepository = parturientRepository;
            _babyRepository = babyRepository;
            _db = db;
        }
        #region 基本方法
        public bool Delete(ServiceDo serviceDo)
        {
            return _serviceDoRepository.Delete(serviceDo);
        }

        public IQueryable<ServiceDo> GetList()
        {
            return _serviceDoRepository.GetList();
        }

        public ServiceDo GetModel(int Id)
        {
            return _serviceDoRepository.GetModel(Id);
        }

        public int Insert(ServiceDo serviceDo)
        {
            return _serviceDoRepository.Insert(serviceDo);
        }

        public bool Update(ServiceDo serviceDo)
        {
            return _serviceDoRepository.Update(serviceDo);
        }
        #endregion

        #region 业务方法

        public Hashtable ListData(ServicesFilter filter)
        {
            // 基本查询 - 以ServiceDo为主表
            var baseQuery = (from serviceDo in _serviceDoRepository.GetList()
                             join serviceVm in _servicesRepository.GetList() on serviceDo.Sid equals serviceVm.Id
                             join contract in _contractRepository.GetList() on serviceDo.Cid equals contract.Id
                             join parturient in _parturientRepository.GetList() on contract.ParturientId equals parturient.Id
                             where serviceDo.IsDelete != 1 // 只显示未删除的记录
                             select new
                             {
                                 serviceDo.Id,
                                 serviceDo.Sid, // 确保包含服务ID
                                 ServiceName = serviceVm.ServiceName,
                                 ServiceType = serviceVm.ServiceType,
                                 RoomName = "房间-" + contract.HomeId,
                                 ParturientName = parturient.ParturientName,
                                 ParturientId = parturient.Id, // 添加产妇ID用于分组
                                 ServiceTime = serviceDo.ServiceTime,
                                 serviceDo.IsDelete,
                                 ServiceThreshold = serviceVm.ServiceThreshold // 直接从Services表获取阈值
                             });

            // 获取所有宝宝信息并按产妇ID分组
            var babiesByParturient = _babyRepository.GetList()
                .Where(b => b.IsDelete != 1)
                .GroupBy(b => b.ParturientId)
                .ToDictionary(g => g.Key, g => string.Join("、", g.Select(b => b.BabyName)));

            // 应用过滤条件
            if (!string.IsNullOrEmpty(filter.ServiceName))
            {
                baseQuery = baseQuery.Where(x => x.ServiceName.Contains(filter.ServiceName));
            }

            if (filter.ServiceType.HasValue)
            {
                baseQuery = baseQuery.Where(x => x.ServiceType == filter.ServiceType.Value);
            }

            if (!string.IsNullOrEmpty(filter.FilterDate))
            {
                DateTime date;
                if (DateTime.TryParse(filter.FilterDate, out date))
                {
                    baseQuery = baseQuery.Where(x => DbFunctions.TruncateTime(x.ServiceTime) == date.Date);
                }
            }

            // 获取总数
            int totalCount = baseQuery.Count();

            // 分页查询并合并宝宝信息
            var pagedQuery = baseQuery
                .OrderBy(x => x.Id)
                .Skip((filter.page - 1) * filter.limit)
                .Take(filter.limit)
                .ToList()
                .Select(x => new
                {
                    x.Id,
                    x.ServiceName,
                    x.ServiceType,
                    x.RoomName,
                    x.ParturientName,
                    BabyNames = babiesByParturient.ContainsKey(x.ParturientId) ?
                               babiesByParturient[x.ParturientId] : "无宝宝信息",
                    ServiceTime = ((DateTime)x.ServiceTime).ToString("yyyy-MM-dd HH:mm:ss"),
                    x.IsDelete,
                    ServiceThreshold = x.ServiceThreshold ?? 0 // 使用直接从Services表获取的阈值
                }).ToList();

            // 统计已完成和未完成数量
            int completedCount = baseQuery.Count(x => x.IsDelete == 1);
            int pendingCount = totalCount - completedCount;

            return new Hashtable
            {
                ["code"] = 0,
                ["msg"] = "",
                ["data"] = pagedQuery,
                ["count"] = totalCount,
                ["stats"] = new
                {
                    total = totalCount,
                    completed = completedCount,
                    pending = pendingCount
                }
            };
        }
        public bool AdjustServiceTime(int id, DateTime newTime)   //调整修改时间
        {
            var service = _serviceDoRepository.GetModel(id);
            if (service == null)
                return false;

            service.ServiceTime = newTime;
            return _serviceDoRepository.Update(service);
        }
        public bool ConfirmService(int id)   //服务确认
        {
            var service = _serviceDoRepository.GetModel(id);
            if (service == null)
                return false;

            service.IsDelete = 1; // 1表示已完成
            return _serviceDoRepository.Update(service);
        }


        #endregion

        #region 公共方法
        public IQueryable<ServiceDo> MakeQueryFilter(IQueryable<ServiceDo> services, ServicesFilter servicesFilter, out int count)  //分页功能
        {
            count = services.Count();
            if (servicesFilter.page != 0 && servicesFilter.limit != 0)
                return services.OrderBy(x => x.Id).Skip((servicesFilter.page - 1) * servicesFilter.limit).Take(servicesFilter.limit);
            else
                return services;
        }
        //服务任务表生成
        public ResMessage ServiceDoAdd(int cId)
        {
            //List<ServiceDo> serviceDos = new List<ServiceDo>();
            ////通过cId合同id在合同表中找出对应的套餐Id pId  入住时间 LiveTime
            //int pId  =_db.Contract.Where(x=>x.Id == cId).Select(x=>x.PackageId).FirstOrDefault();
            ////通过pId 往 套餐服务关系表中找对应的服务ID sID  服务次数
            //List<PackageServices> ps = _db.PackageServices.Where(x=>x.ComboId==pId).ToList();
            ////根据sID 往Services服务表中找出对应服务的 SerStartTime服务第一次开始的时间(起始周) ServiceInterval 服务间隔（天数）
            ////根据入住时间计算每次服务的ServiceTime系统生成的服务时间 将 将对应的合同ID 服务ID ServiceTime 批量插入 serviceDos
            //return ResMessage.Success();
            List<ServiceDo> serviceDos = new List<ServiceDo>();
            // 通过 cId 查找对应的套餐ID pId 和入住时间 LiveTime
            var contract = _db.Contract.Where(x => x.Id == cId).FirstOrDefault();
            if (contract == null)
            {
                return ResMessage.Fail("合同未找到");
            }

            int pId = contract.PackageId;
            DateTime? liveTime = contract.LiveTime;
            // 通过 pId 查找套餐服务列表
            List<PackageServices> ps = _db.PackageServices.Where(x => x.ComboId == pId).ToList();
            if (ps == null || ps.Count == 0)
            {
                return ResMessage.Fail("没有找到套餐服务信息");
            }
            // 遍历每个服务并生成对应的服务任务
            foreach (var packageService in ps)
            {
                // 获取服务ID
                int sID = Convert.ToInt32(packageService.ServiceId);
                int serviceCount = Convert.ToInt32(packageService.ServiceNumber); // 假设PackageServices包含服务次数字段
                // 查找服务详细信息
                var service = _db.Services.Where(x => x.Id == sID).FirstOrDefault();
                // 获取服务开始时间和服务间隔
                int serStartTime = Convert.ToInt32(service.SerStartTime);  // 起始周
                int serviceInterval = Convert.ToInt32(service.ServiceInterval);  // 服务间隔
                // 计算服务时间：根据入住时间和服务起始时间进行偏移
                DateTime serviceTime = liveTime.Value.AddDays((serStartTime - 1) * 7);
                // 根据服务间隔生成服务时间
                // 创建服务任务对象
                for (int i = 0; i < serviceCount; i++)
                {
                    ServiceDo serviceDo = new ServiceDo
                    {
                        Cid = cId,
                        Sid = sID,
                        ServiceTime = serviceTime,
                        CreateTime = DateTime.Now,
                        IsDelete = 0

                    };
                    serviceDos.Add(serviceDo);
                    // 计算下一次服务时间
                    serviceTime = serviceTime.AddDays(serviceInterval);
                }
            }
            // 批量插入服务任务到数据库
            if (serviceDos.Count > 0)
            {
                _db.ServiceDo.AddRange(serviceDos);
                _db.SaveChanges();
            }
            return ResMessage.Success();

        }
        #endregion
    }
}
